<template>
  <div class="filter-panel">
    <div class="filter-line" v-for="(config, key) in filterConfigs" :key="key">
      <div class="filter-label">{{ config.label }}：</div>
      <div class="filter-content">
        <div class="filter-values" :class="{ 'is-collapsed': !config.isExpanded }">
          <el-tag 
            v-for="item in getFilterItems(key)"
            :key="typeof item === 'object' ? item.value : item"
            :class="{ 'is-active': isItemSelected(key, item) }"
            @click="selectFilter(key, typeof item === 'object' ? item.value : item)">
            {{ typeof item === 'object' ? item.label : item }}
          </el-tag>
        </div>
        <div class="expand-wrapper" v-if="shouldShowExpand(key)">
          <div class="expand-button" @click="toggleExpand(key)">
            {{ config.isExpanded ? '收起' : '更多' }}
            <i :class="['el-icon-arrow-' + (config.isExpanded ? 'up' : 'down')]"></i>
          </div>
        </div>
      </div>
    </div>

    <div class="filter-actions">
      <div class="merge-toggle">
        <el-switch
          v-model="mergeSchools"
          @change="handleMergeChange"
          active-text="合并院校成绩"
        />
      </div>
      <el-button @click="handleReset">重置筛选</el-button>
    </div>
  </div>
</template>

<script>
import { reactive, onMounted, toRefs, ref } from 'vue'
import { useDataStore } from '../store/dataStore'

export default {
  name: 'FilterPanel',
  emits: ['filter-change', 'merge-change'],
  setup(_, { emit }) {
    const dataStore = useDataStore()
    const { filterOptions, refreshFilterOptions } = dataStore

    // 初始化过滤器配置
    const filterConfigs = reactive({
      years: { label: '年份', isExpanded: false },
      competitions: { label: '赛项', isExpanded: false },
      tracks: { label: '赛道', isExpanded: false },
      provinces: { label: '省份', isExpanded: false },
      schools: { label: '院校', isExpanded: false }
    })

    const filterForm = reactive({
      years: [],
      competitions: [],
      tracks: [],
      provinces: [],
      schools: []
    })

    const mergeSchools = ref(false)

    onMounted(async () => {
      await refreshFilterOptions()
    })

    const { years, competitions, tracks, provinces, schools } = toRefs(filterOptions)

    // 获取过滤项
    const getFilterItems = (type) => {
      return filterOptions[type] || []
    }

    // 判断是否选中
    const isItemSelected = (type, item) => {
      const value = typeof item === 'object' ? item.value : item
      return filterForm[type].includes(value)
    }

    // 判断是否需要显示展开按钮
    const shouldShowExpand = (type) => {
      const items = getFilterItems(type)
      return items.length > 10 // 超过10个选项时显示展开按钮
    }

    // 切换展开状态
    const toggleExpand = (type) => {
      filterConfigs[type].isExpanded = !filterConfigs[type].isExpanded
    }

    const selectFilter = async (type, value) => {
      const array = filterForm[type]
      const index = array.indexOf(value)
      if (index === -1) {
        array.push(value)
      } else {
        array.splice(index, 1)
      }
      emit('filter-change', filterForm)
      await updateFilterOptions() // 更新可用的筛选选项
    }

    const updateFilterOptions = async () => {
      try {
        // 构建查询参数
        const params = new URLSearchParams()
        Object.entries(filterForm).forEach(([key, values]) => {
          if (values.length > 0) {
            params.append(key, values.join(','))
          }
        })
        
        // 获取更新后的筛选选项
        await refreshFilterOptions(params)
      } catch (error) {
        console.error('Failed to update filter options:', error)
      }
    }

    const handleReset = async () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = []
      })
      emit('filter-change', filterForm)
      await updateFilterOptions() // 重置后更新可用的筛选选项
    }

    const handleMergeChange = (value) => {
      emit('merge-change', value)
    }

    return {
      filterForm,
      filterConfigs,
      years,
      competitions,
      tracks,
      provinces,
      schools,
      selectFilter,
      handleReset,
      getFilterItems,
      isItemSelected,
      shouldShowExpand,
      toggleExpand,
      mergeSchools,
      handleMergeChange
    }
  }
}
</script>

<style>
.filter-panel {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
}

.filter-line {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.filter-label {
  width: 80px;
  color: #666;
  line-height: 32px;
}

.filter-content {
  flex: 1;
  position: relative;
}

.filter-values {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  transition: max-height 0.3s ease-in-out;
  overflow: hidden;
}

.filter-values.is-collapsed {
  max-height: 40px; /* 只显示一行 */
}

.el-tag {
  cursor: pointer;
  user-select: none;
  padding: 0 16px;
  margin: 0;
  height: 32px;
  line-height: 30px;
  border-radius: 2px;
  background: #f5f5f5;
  border: 1px solid #f5f5f5;
  color: #333;
}

.el-tag:hover {
  border-color: #409eff;
  color: #409eff;
}

.el-tag.is-active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}

.filter-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.filter-actions .el-button {
  min-width: 80px;  /* 设置最小宽度 */
}

.expand-wrapper {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}

.expand-button {
  display: inline-flex;
  align-items: center;
  height: 24px;
  padding: 0 12px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 12px;
  color: #666;
  cursor: pointer;
  user-select: none;
  font-size: 12px;
  transition: all 0.3s;
}

.expand-button:hover {
  color: #409eff;
  border-color: #409eff;
}

.expand-button i {
  margin-left: 4px;
  font-size: 12px;
}

/* 移除之前的最后一个tag的右边距 */
.filter-values .el-tag:last-child {
  margin-right: 0;
}

.merge-toggle {
  display: flex;
  align-items: center;
}
</style>
